<template>
  <div v-show="visible" ref="contextMenuRef" class="context-menu" :style="{ left: x + 'px', top: y + 'px' }" @contextmenu.prevent>
    <el-card class="context-menu-card" shadow="always">
      <div class="menu-item" @click="refresh">
        <el-icon><Refresh /></el-icon>
        <span>刷新</span>
      </div>
      <div class="menu-item" @click="maximize">
        <el-icon><FullScreen /></el-icon>
        <span>最大化</span>
      </div>
      <div class="menu-divider"></div>
      <div class="menu-item" @click="closeCurrentTab">
        <el-icon><Remove /></el-icon>
        <span>关闭当前</span>
      </div>
      <div class="menu-item" @click="closeLeftTabs">
        <el-icon><DArrowLeft /></el-icon>
        <span>关闭左侧</span>
      </div>
      <div class="menu-item" @click="closeRightTabs">
        <el-icon><DArrowRight /></el-icon>
        <span>关闭右侧</span>
      </div>
      <div class="menu-item" @click="closeOtherTabs">
        <el-icon><CircleClose /></el-icon>
        <span>关闭其它</span>
      </div>
      <div class="menu-item" @click="closeAllTabs">
        <el-icon><FolderDelete /></el-icon>
        <span>关闭所有</span>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, inject, onMounted, onUnmounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useTabsStore } from "@/stores/modules/tabs";
import { useGlobalStore } from "@/stores/modules/global";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { HOME_URL } from "@/config";

interface Props {
  menuPath?: string;
}

const props = withDefaults(defineProps<Props>(), {
  menuPath: ""
});

const emit = defineEmits<{
  close: [];
}>();

const route = useRoute();
const router = useRouter();
const tabStore = useTabsStore();
const globalStore = useGlobalStore();
const keepAliveStore = useKeepAliveStore();

const visible = ref(false);
const x = ref(0);
const y = ref(0);
const contextMenuRef = ref<HTMLElement>();

// 获取当前路径，优先使用传入的menuPath，否则使用当前路由
const getCurrentPath = () => props.menuPath || route.fullPath;

// 显示右键菜单
const show = (event: MouseEvent) => {
  visible.value = true;
  x.value = event.clientX;
  y.value = event.clientY;
  nextTick(() => {
    if (contextMenuRef.value) {
      const rect = contextMenuRef.value.getBoundingClientRect();
      const viewportWidth = window.innerWidth;
      const viewportHeight = window.innerHeight;
      // 防止菜单超出屏幕边界
      if (x.value + rect.width > viewportWidth) {
        x.value = viewportWidth - rect.width - 10;
      }
      if (y.value + rect.height > viewportHeight) {
        y.value = viewportHeight - rect.height - 10;
      }
    }
  });
};

// 隐藏右键菜单
const hide = () => {
  visible.value = false;
  emit("close");
};

// 刷新页面
const refreshCurrentPage: Function = inject("refresh", () => undefined) as Function;
const refresh = () => {
  const targetPath = getCurrentPath();

  // 如果目标路径不是当前路径，先跳转到目标页面
  if (targetPath !== route.fullPath) {
    router.push(targetPath);
    // 等待路由跳转完成后再刷新
    nextTick(() => {
      if (refreshCurrentPage && typeof refreshCurrentPage === "function") {
        refreshCurrentPage(false);
        nextTick(() => refreshCurrentPage(true));
      } else {
        router.go(0);
      }
    });
  } else {
    // 如果是当前页面，直接刷新
    if (refreshCurrentPage && typeof refreshCurrentPage === "function") {
      setTimeout(() => {
        route.meta.isKeepAlive && keepAliveStore.removeKeepAliveName(targetPath);
        refreshCurrentPage(false);
        nextTick(() => {
          route.meta.isKeepAlive && keepAliveStore.addKeepAliveName(targetPath);
          refreshCurrentPage(true);
        });
      }, 0);
    } else {
      router.go(0);
    }
  }
  hide();
};

// 最大化页面
const maximize = () => {
  const targetPath = getCurrentPath();

  // 如果目标路径不是当前路径，先跳转到目标页面
  if (targetPath !== route.fullPath) {
    router.push(targetPath);
  }

  globalStore.setGlobalState("maximize", true);
  hide();
};

// 关闭标签页
const closeCurrentTab = () => {
  const targetPath = getCurrentPath();

  // 检查目标标签页是否为固定标签页
  const targetTab = tabStore.tabsMenuList.find(tab => tab.path === targetPath);
  if (targetTab && !targetTab.close) return; // 如果是固定标签页则不能关闭

  tabStore.removeTabs(targetPath);
  hide();
};

// 关闭左侧标签
const closeLeftTabs = () => {
  const currentPath = getCurrentPath();
  tabStore.closeTabsOnSide(currentPath, "left");
  hide();
};

// 关闭右侧标签
const closeRightTabs = () => {
  const currentPath = getCurrentPath();
  tabStore.closeTabsOnSide(currentPath, "right");
  hide();
};

// 关闭其他标签
const closeOtherTabs = () => {
  const currentPath = getCurrentPath();
  tabStore.closeMultipleTab(currentPath);
  hide();
};

// 关闭所有标签
const closeAllTabs = () => {
  tabStore.closeMultipleTab();
  router.push(HOME_URL);
  hide();
};

// 点击其他地方关闭菜单
const handleClickOutside = (event: MouseEvent) => {
  if (contextMenuRef.value && !contextMenuRef.value.contains(event.target as Node)) {
    hide();
  }
};

onMounted(() => {
  document.addEventListener("click", handleClickOutside);
  document.addEventListener("scroll", hide);
  window.addEventListener("resize", hide);
});

onUnmounted(() => {
  document.removeEventListener("click", handleClickOutside);
  document.removeEventListener("scroll", hide);
  window.removeEventListener("resize", hide);
});

defineExpose({
  show,
  hide
});
</script>

<style scoped lang="scss">
.context-menu {
  position: fixed;
  z-index: 9999;

  .context-menu-card {
    min-width: 110px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    :deep(.el-card__body) {
      padding: 4px 0;
    }

    .menu-item {
      display: flex;
      align-items: center;
      padding: 6px 12px;
      cursor: pointer;
      font-size: 13px;
      line-height: 1.4;
      transition: all 0.2s;
      color: var(--el-text-color-regular);

      &:hover {
        background-color: var(--el-color-primary-light-9);
        color: var(--el-color-primary);
      }

      &:first-child {
        border-radius: 4px 4px 0 0;
      }

      &:last-child {
        border-radius: 0 0 4px 4px;
      }

      .el-icon {
        margin-right: 6px;
        font-size: 13px;
        width: 14px;
        height: 14px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }

    .menu-divider {
      height: 1px;
      background-color: var(--el-border-color-lighter);
      margin: 2px 8px;
    }
  }
}
</style>
